//导入express
const express = require('express');
// 导入http模块
const http=require('http');
// 引入xml2js
const xml2js = require("xml2js");
const parse = new xml2js.Parser({ explicitArray: false });
const build=new xml2js.Builder({rootName:'xml',cdata:true,headless:true});
// 创建express服务器
const app = express();
// 注册路由
app.get('/', (req, res) => {
    // 接收微信服务器通过get方式发送的echostr参数, 并且原样返回给微信服务器
    var echostr = req.query.echostr;
    console.log('微信服务器请求了:' + echostr);
    res.send(echostr);
});
// 注册post路由, 接收微信发送的消息
app.post('/', (req, res) => {
    // console.log('您有新的微信消息, 请注意查收');
    var dataBuffer = [];
    req.on('data', function (chunk) {
        dataBuffer.push(chunk);
    });
    req.on('end', function () {
        // 将数据块拼接起来
        var buffer = Buffer.concat(dataBuffer);
        //  将二进制数据转换成字符串格式
        var reqXml = buffer.toString();
        var reqObj = parse.parseString(reqXml, (err, result) => {
            var xml=result.xml;
            var content='';
            switch(xml.MsgType){
                case 'text':
                    content='您发送了一个文本消息';    
                break;
                case 'image':
                    content='您发送了一个图片消息';    
                break;
            }
            var returnMsg={
                ToUserName:xml.FromUserName,
                FromUserName:xml.ToUserName,
                CreateTime:+new Date(),
                MsgType:'text',
                Content:content
            }
            res.send(build.buildObject(returnMsg));
        });
    });

});
// 开启服务器
app.listen('8888', () => {
    console.log('server running at http://natappfree.cc');
});